/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/*
 Document   : countrySelector
 Created on : 17/10/2014, 10:37:20 AM
 Author     : Luis.Parada
 */

absoluteURL = "http://tienda.nexsysla.com/webapp/wcs/stores/servlet/";

var storeId = GetURLParameter('storeId');
if (typeof storeId === 'undefined') {
    storeId = "10152";
}
    
var selectorCountry;
var selectorCountrySort = [];

function getSelectorCountry() {
    xmlhttp = new XMLHttpRequest();
    var url = "countries.json";
    xmlhttp.onreadystatechange = callbackSelectorCountry;
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function callbackSelectorCountry() {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        selectorCountry = JSON.parse(xmlhttp.responseText);
        for(var i in selectorCountry){
            if(i === storeId){
                addSelectedCountry(selectorCountry[i].pais, selectorCountry[i].codigo);
            }else{
                selectorCountrySort.push([selectorCountry[i].codigo, 
                    {"pais": selectorCountry[i].pais, "storeId": i}]);
            }            
        }
        selectorCountrySort.sort();
        for(var i in selectorCountrySort){
            addCountry(selectorCountrySort[i][1].pais, selectorCountrySort[i][0], 
            selectorCountrySort[i][1].storeId);
        }
    }
}

function GetURLParameter(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1];
        }
    }
}

var addCountry = function (country, code, storeId) {
    $("#countrySelector").append('<li><a href="' + absoluteURL + 'StoreView?storeId=' + storeId + '">'
            + '<span class="country-text">' + country + '</span>'
            + '<span class="country-' + code + ' country-img"></span></a></li>');
};

var addSelectedCountry = function (country, code) {
    $("#formcss-em-select-0").append('<span class="country-text">' + country + '</span>'
            +'<span class="country-'+code+' country-img"></span>');
};

$(function () {
    
    $("#formcss-em-select-0").click(function () {
        if ($("#countrySelector").is(":visible")) {
            $("#countrySelector").slideUp();
        } else {
            $("#countrySelector").slideDown();
        }
    });
    
    getSelectorCountry();
    
});

